package com.example.tenant.config;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.MappedStatement;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * MyBatis-Plus 插件：
 * 在执行 insert/update 前，截断带 @MaxLength 的 String 字段
 */
public class MaxLengthInnerInterceptor implements InnerInterceptor {

    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
        handleParameter(parameter);
    }

    @Override
    public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
        ParameterHandler parameterHandler = sh.getParameterHandler();
        Object parameterObject = parameterHandler.getParameterObject();
        handleParameter(parameterObject);
    }

    private void handleParameter(Object parameter) {
        if (parameter == null)
            return;

        Class<?> clazz = parameter.getClass();
        while (clazz != null && clazz != Object.class) {
            for (Field field : clazz.getDeclaredFields()) {
                MaxLength ann = field.getAnnotation(MaxLength.class);
                if (ann != null && field.getType() == String.class) {
                    boolean accessible = field.isAccessible();
                    try {
                        field.setAccessible(true);
                        String val = (String) field.get(parameter);
                        if (val != null && val.length() > ann.value()) {
                            field.set(parameter, val.substring(0, ann.value()));
                        }
                    } catch (IllegalAccessException ignored) {
                    } finally {
                        field.setAccessible(accessible);
                    }
                }
            }
            clazz = clazz.getSuperclass();
        }
    }
}

